package org.jeecg.modules.course.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.course.entity.AstuCourse;
import org.jeecg.modules.course.service.IAstuCourseService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.experiment.entity.AstuExperiment;
import org.jeecg.modules.experiment.service.IAstuExperimentService;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.vo.AstuCoursePage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 课程表
 * @Author: jeecg-boot
 * @Date:   2021-10-22
 * @Version: V1.0
 */
@Api(tags="课程表")
@RestController
@RequestMapping("/course/astuCourse")
@Slf4j
public class AstuCourseController extends JeecgController<AstuCourse, IAstuCourseService> {
	@Autowired
	private IAstuCourseService astuCourseService;
	 @Autowired
	 private IAstuExperimentService astuExperimentService;

	/**
	 * 分页列表查询
	 *
	 * @param astuCourse
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//教师只能看到自己的课程
	@AutoLog(value = "课程表-分页列表查询")
	@ApiOperation(value="课程表-分页列表查询", notes="课程表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(AstuCourse astuCourse,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<AstuCourse> queryWrapper = QueryGenerator.initQueryWrapper(astuCourse, req.getParameterMap());
		Page<AstuCourse> page = new Page<AstuCourse>(pageNo, pageSize);
		IPage<AstuCourse> pageList = astuCourseService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param astuCoursePage
	 * @return
	 */
	@AutoLog(value = "课程表-添加")
	@ApiOperation(value="课程表-添加", notes="课程表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody AstuCoursePage astuCoursePage) {
		AstuCourse astuCourse = new AstuCourse();
		//获取所有的课程号
		List<AstuCourse> astuCourses = astuCourseService.selectAllCourseNum();
		//获取所有的实验号
		List<AstuExperiment> astuExperiments = astuExperimentService.selectAllExperimentNum();
		//输入的课程号
		String courseNumber1 = astuCoursePage.getCourseNumber();
		for (AstuCourse astuCours : astuCourses) {
			//数据库中的课程号
			String courseNumber = astuCours.getCourseNumber();
			//输入的课程号存在，添加失败
			if (courseNumber.equals(courseNumber1)){
				return Result.error("该课程号已存在，请重新新建课程！");
			}
			//输入的实验号存在，添加失败
			for (AstuExperiment astuExperiment : astuExperiments) {
				//输入的实验号
				List<AstuExperiment> astuExperimentList = astuCoursePage.getAstuExperimentList();
				for (AstuExperiment experiment : astuExperimentList) {
					String experimentNum = experiment.getExperimentSerialNumber();
					//数据库中的实验号
					String experimentSerialNumber = astuExperiment.getExperimentSerialNumber();
					if (experimentSerialNumber.equals(experimentNum)){
						return Result.error("该实验号已存在，请重新新建实验！");
					}
				}
			}
		}
		BeanUtils.copyProperties(astuCoursePage, astuCourse);
		astuCourseService.saveMain(astuCourse, astuCoursePage.getAstuExperimentList());
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param astuCoursePage
	 * @return
	 */
	@AutoLog(value = "课程表-编辑")
	@ApiOperation(value="课程表-编辑", notes="课程表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody AstuCoursePage astuCoursePage) {
		AstuCourse astuCourse = new AstuCourse();
		BeanUtils.copyProperties(astuCoursePage, astuCourse);
		String id = astuCourse.getId();
		System.out.println("id-------->"+id);
		AstuCourse astuCourseEntity = astuCourseService.getById(astuCourse.getId());
		if(astuCourseEntity==null) {
			return Result.error("未找到对应数据");
		}
		astuCourseService.updateMain(astuCourse, astuCoursePage.getAstuExperimentList());
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "课程表-通过id删除")
	@ApiOperation(value="课程表-通过id删除", notes="课程表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		astuCourseService.delMain(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "课程表-批量删除")
	@ApiOperation(value="课程表-批量删除", notes="课程表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.astuCourseService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "课程表-通过id查询")
	@ApiOperation(value="课程表-通过id查询", notes="课程表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		AstuCourse astuCourse = astuCourseService.getById(id);
		if(astuCourse==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(astuCourse);
	}

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "实验表-通过主表ID查询")
	 @ApiOperation(value="实验表-通过主表ID查询", notes="实验表-通过主表ID查询")
	 @GetMapping(value = "/queryAstuExperimentByMainId")
	 public Result<?> queryAstuExperimentListByMainId(@RequestParam(name="id",required=true) String id) {
		 List<AstuExperiment> astuExperimentList = astuExperimentService.selectByMainId(id);
		 IPage <AstuExperiment> page = new Page<>();
		 page.setRecords(astuExperimentList);
		 page.setTotal(astuExperimentList.size());
		 return Result.OK(page);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param astuCourse
    */
    @RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, AstuCourse astuCourse) {
		// Step.1 组装查询条件查询数据
		QueryWrapper<AstuCourse> queryWrapper = QueryGenerator.initQueryWrapper(astuCourse, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//Step.2 获取导出数据
		List<AstuCourse> queryList = astuCourseService.list(queryWrapper);
		// 过滤选中数据
		String selections = request.getParameter("selections");
		List<AstuCourse> astuCourseList = new ArrayList<AstuCourse>();
		if(oConvertUtils.isEmpty(selections)) {
			astuCourseList = queryList;
		}else {
			List<String> selectionList = Arrays.asList(selections.split(","));
			astuCourseList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
		}

		// Step.3 组装pageList
		List<AstuCoursePage> pageList = new ArrayList<AstuCoursePage>();
		for (AstuCourse main : astuCourseList) {
			AstuCoursePage vo = new AstuCoursePage();
			BeanUtils.copyProperties(main, vo);
			List<AstuExperiment> astuExperimentList = astuExperimentService.selectByMainId(main.getId());
			vo.setAstuExperimentList(astuExperimentList);
			pageList.add(vo);
		}

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "课程表列表");
		mv.addObject(NormalExcelConstants.CLASS, AstuCoursePage.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("课程表数据", "导出人:"+sysUser.getRealname(), "课程表"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<AstuCoursePage> list = ExcelImportUtil.importExcel(file.getInputStream(), AstuCoursePage.class, params);
				for (AstuCoursePage page : list) {
					AstuCourse po = new AstuCourse();
					BeanUtils.copyProperties(page, po);
					astuCourseService.saveMain(po, page.getAstuExperimentList());
				}
				return Result.OK("文件导入成功！数据行数:" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(),e);
				return Result.error("文件导入失败:"+e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.OK("文件导入失败！");
	}
}
